<?php
/**
 * Created by PhpStorm.
 * User: 君贤
 * Date: 14-1-16
 * Time: 下午2:05
 */

namespace app\modules\admin\components;

// 集合管理类
class Category {
    // 组合一维数组
    static public function unlimitedForLevel ($cate, $parent='pid', $html = '----', $suffix = '|', $pid = null, $level = 0) {
        $arr = array();
        foreach ($cate as $v){
            if($v[$parent] == $pid){
                $v['level'] = $level + 1;
                $v['prefix'] = str_repeat($html, $level) . ($level ? $suffix : '');
                $arr[] = $v;
                $arr = array_merge($arr, self::unlimitedForLevel($cate, $parent, $html, $suffix, $v['id'], $level + 1));
            }
        }
        return $arr;
    }

    // 组合多位数组
    static public function unlimitedForLayer($cate,$name='child', $pid = 0) {
        $arr = array();
        foreach ($cate as $v){
            if($v['pid'] == $pid){
                $v[$name] = self::unlimitedForLayer($cate, $name, $v['id']);
                $arr[] = $v;
            }
        }
        return $arr;
    }

    // 传递一个子分类ID返回所有的父级分类
    static public function getParents($cate, $id){
        $arr = array();
        foreach ($cate as $v){
            if($v['id'] == $id){
                $arr[] = $v;
                $arr = array_merge(self::getParents($cate, $v['pid']), $arr);
            }
        }
        return $arr;
    }

    // 传递一个父级分类ID返回所有的子级分类
    static public function getChilds($cate, $pid, $name='child'){
        $arr = array();
        foreach ($cate as $v){
            if($v['pid'] == $pid){
                $v[$name] = self::getChilds($cate, $v['id'], $name);
                $arr[] = $v;
            }
        }
        return $arr;
    }

    // 传递一个父级分类ID返回所有的子级ID
    static public function getChildsId($cate, $pid){
        $arr = array();
        foreach ($cate as $v) {
            if($v['pid'] == $pid){
                $arr[] = $v['id'];
                $arr = array_merge($arr, self::getChildsId($cate, $v['id']));
            }
        }
        return $arr;
    }
} 